package com.base.app_core.ui;


import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;

import com.base.app_core.R;
import com.base.app_core.R2;
import com.base.app_core.base.impl.BaseActivity;
import com.base.app_core.service.pressenter.NullPressenter;
import com.base.app_core.util.AppConstants;
import com.base.app_core.util.XYBAUtils;
import com.base.app_core.util.Preferences;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.StringUtils;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;


public abstract class WebActivity extends BaseActivity<NullPressenter> {

    @BindView(R2.id.web_content)
    protected WebView webContent;
    @BindView(R2.id.toolbar)
    protected Toolbar toolbar;
    @BindView(R2.id.right_menu_fun)
    ImageView imageView;
    private WebSettings webSettings;
    private Map<String, String> requestHeader = new HashMap<>();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_web_layout;
    }

    public void initWebView() {
        webContent.setFocusable(false);
        String jwtToken = Preferences.getDefault().getString(AppConstants.SP.JWTOKEN, null);

        if (!StringUtils.isEmpty(jwtToken)) {
            requestHeader.put("Authorization", "Bearer " + jwtToken);
            requestHeader.put("Platform", "Android");
            requestHeader.put("method", "1");
            requestHeader.put("version", XYBAUtils.getVersion(this));
            requestHeader.put("identifi", Preferences.getDefault().getString(AppConstants.SP.IMEI, ""));
        }
        webContent.loadUrl(getUrl(), requestHeader);
        webSettings = webContent.getSettings();
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setBuiltInZoomControls(true);

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {//少于4.4（不包括4.4）用这个
            webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        } else {
            //适应屏幕，大于等于4.4用这个
            webSettings.setUseWideViewPort(true);
        }
        webSettings.setJavaScriptEnabled(true);
        webSettings.setLoadsImagesAutomatically(true);
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSettings.setBlockNetworkImage(true);

        if (NetworkUtils.isConnected()) {
            webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);//根据cache-control决定是否从网络上取数据。
        } else {
            webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);//没网，则从本地获取，即离线加载
        }
        webContent.setWebViewClient(new HttpsWebViewClient());
        webContent.addJavascriptInterface(new AndroidToJs(), "jml");
        showProgress();
        webContent.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView webView, final String s) {
                super.onReceivedTitle(webView, s);
                setToolBar(s);

                final boolean isShare = getIntent().getBooleanExtra(AppConstants.EXTRA.IS_SHARE, false);
                if (isShare) {
                    imageView.setVisibility(View.VISIBLE);
                    imageView.setImageResource(R.mipmap.ic_share_notice);
                    imageView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            UMWeb web = new UMWeb(getUrl());//本地文件
                            web.setTitle(s);
                            String extra = getIntent().getStringExtra(AppConstants.EXTRA.WEB_CONTENT);
                            if (StringUtils.isEmpty(extra)) {
                                web.setDescription("");
                            } else {
                                web.setDescription(extra);
                            }
                            web.setThumb(new UMImage(WebActivity.this, R.mipmap.ic_launcher_logo));
                            new ShareAction(WebActivity.this)
                                    .setDisplayList(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE)//传入平台
                                    .withText("hello")//分享内容
                                    .withMedia(web)
                                    .setCallback(new UMShareListener() {
                                        @Override
                                        public void onStart(SHARE_MEDIA share_media) {

                                        }

                                        @Override
                                        public void onResult(SHARE_MEDIA share_media) {
                                            showToast("分享成功");
                                        }

                                        @Override
                                        public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                                        }

                                        @Override
                                        public void onCancel(SHARE_MEDIA share_media) {
                                        }
                                    })//回调监听器
                                    .open();
                        }
                    });
                } else {
                    imageView.setVisibility(View.GONE);
                }
                dismissProgress();
            }

        });

        //根据屏幕的宽度进行适配
        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        if (width > 650) {
            this.webContent.setInitialScale(190);
        } else if (width > 520) {
            this.webContent.setInitialScale(160);
        } else if (width > 450) {
            this.webContent.setInitialScale(140);
        } else if (width > 300) {
            this.webContent.setInitialScale(120);
        } else {
            this.webContent.setInitialScale(100);
        }
    }

    protected abstract String getUrl();


    private class HttpsWebViewClient extends WebViewClient {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            webSettings.setBlockNetworkImage(false);
        }

        @Override
        public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {
//            super.onReceivedSslError(webView, sslErrorHandler, sslError);
            sslErrorHandler.proceed();
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (parseScheme(url)) {
                try {
                    Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
                    intent.addCategory("android.intent.category.BROWSABLE");
                    intent.setComponent(null);
                    startActivity(intent);
                } catch (Exception e) {

                }
            } else {
                view.loadUrl(url);
            }

            return true;
        }

        public boolean parseScheme(String url) {
            if (url.contains("platformapi/startapp") || url.contains("alipay")) {
                return true;
            } else if (url.contains("web-other")) {
                return false;
            } else {
                return false;
            }
        }
    }

    protected boolean shouldOverrideUrlLoading(WebView view, String url) {
        return true;
    }

    @Override
    protected void initView() {
        super.initView();
        initWebView();
    }
}
